from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from .models import *
from .serializer import *
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination

# Create your views here.
# 分页的视图
class MyPagination(PageNumberPagination):

    page_size = 2
    max_page_size = 10

    page_query_param = "size"
    page_size_query_param = "pagesize"


# 优惠券的视图集
class CouponViewSet(ModelViewSet):
    queryset = Coupon.objects.all()
    serializer_class = CouponSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"
    # pagination_class = MyPagination
    def create(self, request, *args, **kwargs):

        # 获取数据
        name = request.data.get("name")

        names = Coupon.objects.filter(name=name)

        if names:
            return Response({"code":400, "msg":"优惠券已添加"})
        else:
            ser = self.get_serializer(data=request.data)
            ser.is_valid()
            ser.save()
            return Response({"code": 200, "msg": "添加成功"})


# 优惠券类型的视图
class CouponTypeListAPIView(ListAPIView):
    queryset = CouponType.objects.all()
    serializer_class = CouponTypeSer
